//
//  QMyIncomeVC.m
//  QoilPublic
//
//  Created by 杨凯 on 2017/2/16.
//  Copyright © 2017年 杨凯. All rights reserved.
//

#import "CashVC.h"
#import "QIncomeCell.h"
#import "CashCell.h"
//#import "QIncomePhoneCell.h"
//#import "QMySuperiorVC.h"

@interface CashVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic,strong)UITableView *tbView;
@property (nonatomic,strong)QIncomeModel *model;
@property (nonatomic,strong)UIButton *agreeBtn;
@property (nonatomic,copy)NSString *moneyString;

@end

@implementation CashVC

- (id)init{
    self = [super init];
    if (self) {
        
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"我要提现";
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self RequestIfNoCardData];
    [self requestData];
    [self createUI];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AddNewCardNotification) name:@"AddNewCardNotification" object:nil];
}

- (void)AddNewCardNotification{
    [self RequestIfNoCardData];
}

//获取用户佣金余额
- (void)requestData{
    NSString * url =[QParamService urlWithAction:@"getMyCommission"];
    NSDictionary * para =[QParamService getMyCommission];
    [[QHttpManager sharedManager] POST:url parameterMD5:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error) {
            NSLog(@"-------error:%@--------",error);
            return ;
        }
        QBaseModel * baseModel =[QBaseModel objectFromDict:dict];
        NSLog(@"-----ok--dic:%@",dict);
        if ([baseModel.result isEqualToString:@"success"]) {
            _model = [QIncomeModel objectFromDict:baseModel.items];
            [_tbView reloadData];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:baseModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}
-(void)createUI
{
    self.view.clipsToBounds = YES;
    [self.view addSubview:self.tbView];
    
    //提交
    UIView * footer =[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    _agreeBtn =[QViewUtility createButtonWithFrame:CGRectMake(40, 20, kScreenWidth - 80, 45) font:Ksize17 title:@"提交" titleColor:[UIColor whiteColor] backgroundColor:[QColorUtility defaultBlueColor]];
    [_agreeBtn addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    _agreeBtn.layer.cornerRadius = 7;
    _agreeBtn.clipsToBounds = YES;
    [footer addSubview:_agreeBtn];
    self.tbView.tableFooterView = footer;
    
    [self.tbView registerNib:[UINib nibWithNibName:@"QIncomeCell" bundle:nil] forCellReuseIdentifier:@"QIncomeCell"];
    [self.tbView registerNib:[UINib nibWithNibName:@"CashCell" bundle:nil] forCellReuseIdentifier:@"CashCell"];
}
- (void)submitAction{
    
    [self.view endEditing:YES];
    
    if ([self.moneyString isEqualToString:@""]||self.moneyString == nil) {
        [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"请输入提现金额" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        return;
    }
    
    [self RequestTiXianData];
    
    
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    
    //去掉透明后导航栏下边的黑边
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    //半透明
    self.navigationController.navigationBar.translucent = NO;
   
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row ==0) {
        return 200;
    }else{
        return 180;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        QIncomeCell * cell =[tableView dequeueReusableCellWithIdentifier:@"QIncomeCell" forIndexPath:indexPath];
        
        cell.model = _model;
        return cell;
            
    }else{
         CashCell*cell = [tableView dequeueReusableCellWithIdentifier:@"CashCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        //__block CashVC *wself = self;
        NSDictionary *tmpDic = [_cardInfo objectAtIndex:0];
        NSString *cardNum = [tmpDic objectForKey:@"number"];
        NSString *imgString = [tmpDic objectForKey:@"img"];
        cell.cardLabel.text = cardNum;
        [cell.tiXianImgView sd_setImageWithURL:[NSURL URLWithString:imgString] placeholderImage:[UIImage imageNamed:@""]];
        
        [cell.moneyText addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
        cell.moneyText.delegate = self;
//         NSString *showString = @"";
//        if ([[tmpDic objectForKey:@"typeId"]intValue] == 2||[[tmpDic objectForKey:@"typeId"]intValue] == 1) {
//            if (!(cardNum == nil||[cardNum isEqualToString:@""])) {
//                showString = cardNum;
//            }else{
//                showString = @"00000000000";
//            }
//            
//        cell.cardLabel.text = showString;
//        [cell.tiXianImgView sd_setImageWithURL:[NSURL URLWithString:imgString] placeholderImage:[UIImage imageNamed:@""]];
//            
//        }else {
        
//            showString = [cardNum substringFromIndex:cardNum.length - 4];
//           
//            cell.cardLabel.text = [NSString stringWithFormat:@"**** **** **** %@",showString];
//            [cell.tiXianImgView sd_setImageWithURL:[NSURL URLWithString:imgString] placeholderImage:[UIImage imageNamed:@""]];
//        }
        
        return cell;
    }
    
}
- (void)textFieldWithText:(UITextField *)textField
{
    NSLog(@"text:%@",textField.text);
    self.moneyString = textField.text;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (void)RequestIfNoCardData{
    NSString *url = [QParamService urlWithAction:@"userinfo/getUssBank"];
    NSDictionary *para= [QParamService GainIsOrNoBanks];
    [QViewUtility showMBHudToView:self.view hideBg:YES];
    [QViewUtility disMissNoRecordInVC:self];
    [QViewUtility disMissNoNetWorkInVC:self];
    [[QHttpManager sharedManager] POST:url parameterMD5:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [_tbView.mj_header endRefreshing];
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            if([QUserInfo sharedInfo].isHaveNetWork == NO){
                [QViewUtility showNoNetWorkInView:_tbView];
            }
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            
            NSArray *arr = basModel.items;
            if (arr.count>0) {
                self.cardInfo = arr.mutableCopy;
                [self.tbView reloadData];
            }else{
                
                
                
            }
            
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}
- (void)RequestTiXianData{
    NSString *url = [QParamService urlWithAction:@"userinfo/getWithdrawals"];
    NSDictionary *cardInfo = [self.cardInfo objectAtIndex:0];
    NSString *cardId = [cardInfo objectForKey:@"typeId"];
    NSString *cardNum = [cardInfo objectForKey:@"number"];
    NSString *money = _moneyString;
    NSDictionary *para= [QParamService GainTiXianWithCardId:cardId CardNum:cardNum Money:money];
    [QViewUtility showMBHudToView:self.view hideBg:YES];
    [QViewUtility disMissNoRecordInVC:self];
    [QViewUtility disMissNoNetWorkInVC:self];
    [[QHttpManager sharedManager] POST:url parameterMD5:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [_tbView.mj_header endRefreshing];
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            if([QUserInfo sharedInfo].isHaveNetWork == NO){
                [QViewUtility showNoNetWorkInView:_tbView];
           
            }
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"提交成功,系统将在24小时内处理到账" btnTitle:showAlertBtnTitle type:1 myBlock:^{
                
                [self.navigationController popViewControllerAnimated:YES];
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"TiXianActionNotification" object:nil];
            }];
            
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
#pragma mark TextField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
#pragma mark - Getter/Setter
- (UITableView*)tbView {
    if (!_tbView) {
        _tbView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
        _tbView.dataSource = self;
        _tbView.delegate = self;
        _tbView.backgroundColor = [UIColor whiteColor];
        _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tbView;
}

#define myDotNumbers     @"0123456789.\n"
#define myNumbers          @"0123456789\n"

#pragma mark - textFieldDelegate

// textField输入金额的限制,小数点前9位,后面两位,如果不加小数点,最大位数是9位,加上小数点,最大位数是12位,超出最大位数可删除

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    // 判断是否输入内容，或者用户点击的是键盘的删除按钮
    if (![string isEqualToString:@""]) {
        NSCharacterSet *cs;
        // 小数点在字符串中的位置 第一个数字从0位置开始
        
        NSInteger dotLocation = [textField.text rangeOfString:@"."].location;
        
        // 判断字符串中是否有小数点，并且小数点不在第一位
        
        // NSNotFound 表示请求操作的某个内容或者item没有发现，或者不存在
        
        // range.location 表示的是当前输入的内容在整个字符串中的位置，位置编号从0开始
        
        if (dotLocation == NSNotFound && range.location != 0) {
            
            // 取只包含“myDotNumbers”中包含的内容，其余内容都被去掉
            
            /* [NSCharacterSet characterSetWithCharactersInString:myDotNumbers]的作用是去掉"myDotNumbers"中包含的所有内容，只要字符串中有内容与"myDotNumbers"中的部分内容相同都会被舍去在上述方法的末尾加上invertedSet就会使作用颠倒，只取与“myDotNumbers”中内容相同的字符
             */
            cs = [[NSCharacterSet characterSetWithCharactersInString:myDotNumbers] invertedSet];
            if (range.location >= 9) {
                NSLog(@"单笔金额不能超过亿位");
                if ([string isEqualToString:@"."] && range.location == 9) {
                    return YES;
                }
                return NO;
            }
        }else {
            
            cs = [[NSCharacterSet characterSetWithCharactersInString:myNumbers] invertedSet];
            
        }
        // 按cs分离出数组,数组按@""分离出字符串
        
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        
        BOOL basicTest = [string isEqualToString:filtered];
        
        if (!basicTest) {
            
            NSLog(@"只能输入数字和小数点");
            
            return NO;
            
        }
        
        if (dotLocation != NSNotFound && range.location > dotLocation + 2) {
            
            NSLog(@"小数点后最多两位");
            
            return NO;
        }
        if (textField.text.length > 11) {
            
            return NO;
            
        }
    }
    return YES;
}
@end
